package com.yi.mall.user.service.impl;

import com.yi.mall.common.utils.ResponseEnum;
import com.yi.mall.common.utils.UserIpUtils;
import com.yi.mall.common.model.Login;
import com.yi.mall.common.model.UserInfo;
import com.yi.mall.common.model.UserLoginLog;
import com.yi.mall.user.service.ILogin;
import jakarta.servlet.http.HttpServletRequest;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginImpl implements ILogin {
    @Autowired
    private UserInfoServiceImpl userInfoService;
    @Autowired
    private UserLoginLogServiceImpl userLoginLogService;
    @Override
    public UserInfo login(Login login, HttpServletRequest request) {
        //1.根据用户名查询用户信息
        UserInfo userinfo = userInfoService.getUserInfoByUserName(login.getUsername());
        //2.判断用户是否存在
        if (userinfo == null) {
            throw new RuntimeException(ResponseEnum.USER_ACCOUNT_FORBIDDEN.getMsg());
        }
        String password= login.getPassword();
        //3.判断密码是否正确
        if(!BCrypt.checkpw(password, userinfo.getPassword())) {
            throw new RuntimeException(ResponseEnum.USER_PASSWORD_ERROR.getMsg());
        }
        //4.记录登录日志
        String username=login.getUsername();
        String ip = UserIpUtils.getIpAddr(request);
        UserLoginLog userloginlog = new UserLoginLog();
        userloginlog.setUserId(userinfo.getId());
        userloginlog.setIp(ip);
        userLoginLogService.save(userloginlog);
        return userinfo;
    }
}
